import {Component} from '@angular/core';

import {Events, NavController, AlertController, NavParams, ViewController, PopoverController} from 'ionic-angular';

import {User} from "../../providers/user";
import {AppData} from "../../providers/app-data";
import {Response} from "@angular/http";


@Component({
  template: `
    <ion-list>
      <button ion-item (click)="close()" class="button-danger">删除帐号</button>
    </ion-list>
  `
})
class DeleteUserPopover {

  constructor(public viewCtrl: ViewController, public events: Events) {
  }

  //do not inject UserDetailPage here, that will cause this popover lays behind UserDetailPage
  close() {
    this.viewCtrl.dismiss().then(()=> {
      this.events.publish('deleteUser:delete');
    });
  }

}

@Component({
  templateUrl: 'build/pages/user-detail/user-detail.html'
})

export class UserDetailPage {
  user: User;

  constructor(public popoverCtrl: PopoverController, public events: Events, public navCtrl: NavController, public alertCtrl: AlertController, public navParams: NavParams, public appData: AppData) {
    this.user = this.navParams.data;
  }

  onSaveUser() {
    this.appData.saveUser(this.user).then((res: Response) => {
      let result = res.json().result;
      if (result === "success") {
        this.goToUserManager();
      } else {
        let alert = this.alertCtrl.create({
          title: '添加帐号失败，请稍候再试！',
          buttons: [{
            text: 'OK',
            handler: () => {
              // close the sliding item
            }
          }]
        });
        // now present the alert on top of all other content
        alert.present();
      }
    });
  }

  onDeleteUser() {
    this.appData.deleteUser(this.user).then((res: Response) => {
      let result = res.json().result;
      if (result === "success") {
        this.goToUserManager();
      } else {
        let alert = this.alertCtrl.create({
          title: '删除帐号失败，请稍候再试！',
          buttons: [{
            text: 'OK',
            handler: () => {
              // close the sliding item
            }
          }]
        });
        // now present the alert on top of all other content
        alert.present();
      }
    });
  }

  goToUserManager() {
    this.navCtrl.pop();
  }

  presentPopover(event) {
    let popover = this.popoverCtrl.create(DeleteUserPopover);
    popover.present({ev: event});
  }

  private _deleteSub: () => void;

  ionViewDidEnter() {
    this._deleteSub = () => {
      this.onDeleteUser();
    };
    this.events.subscribe('deleteUser:delete', this._deleteSub);
  }

  //make sure events are unsubscribed
  ionViewWillLeave() {
    if (this._deleteSub) {
      this.events.unsubscribe('deleteUser:delete', this._deleteSub);
      this._deleteSub = undefined;
    }
  }


}
